package org.hidaron.asyncdownloader.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

/**
 * 
 * @author hidaron
 * @date 2014-1-8
 * 
 */
public class FileUtils {
	private static final int DEFAULT_BUFFER_SIZE = 1024;

	/**
	 * 拷贝文件
	 * 
	 * @param inputStream
	 * @param outputStream
	 * @throws IOException
	 */
	public static void copy(InputStream inputStream, OutputStream outputStream)
			throws IOException {
		if (null == inputStream || null == outputStream) {
			return;
		}
		byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
		BufferedInputStream bis = new BufferedInputStream(inputStream);
		BufferedOutputStream bos = new BufferedOutputStream(outputStream);
		int length = 0;
		while ((length = bis.read(buffer)) != -1) {
			bos.write(buffer, 0, length);
		}
		bis.close();
		bos.close();
	}

	/**
	 * 拷贝文件
	 * 
	 * @param resDir
	 * @param desDir
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void copy(File resDir, File desDir)
			throws FileNotFoundException, IOException {
		copy(new FileInputStream(resDir), new FileOutputStream(desDir));
	}

	/**
	 * 拷贝文件
	 * 
	 * @param resDirPath
	 * @param desDirPath
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void copy(String resDirPath, String desDirPath)
			throws FileNotFoundException, IOException {
		copy(new FileInputStream(resDirPath), new FileOutputStream(desDirPath));
	}
	
	/**
	 * 安装APP
	 * 
	 * @param context
	 * @param filePath
	 */
	public static void install(Context context, String filePath) {
	    Intent i = new Intent(Intent.ACTION_VIEW);
	    i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
	    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    context.startActivity(i);
	}
}
